package com.ruoyi.web.core.tag;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.AppCtx;
import com.ruoyi.common.core.bo.ResponseData;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.web.core.anno.TagName;
import org.beetl.core.tag.GeneralVarTagBinding;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * 通用radio标签
 */
@TagName("radio")
@Component
public class RadioTag extends GeneralVarTagBinding {

    @Override
    public void render() {

        Object id = getAttributeValue("id");
        Object msg = getAttributeValue("msg");
        Object value = getAttributeValue("value");

        Object values = getAttributeValue("values");
        Object labels = getAttributeValue("labels");

        //选项：全部的文本
        Object all = getAttributeValue("all");
        //从接口获得，接口返回数据格式：[{name:'',value:''},...]
        Object api = getAttributeValue("api");
        Object dict = getAttributeValue("dict");

        if(api != null){//通过api渲染

            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            String domain = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();

            String result = HttpUtil.post(domain+"/"+api.toString(),new HashMap<>());

            if(StrUtil.isNotEmpty(result)){
                ResponseData responseData = JSONUtil.toBean(result, ResponseData.class);
                JSONArray array = JSONUtil.parseArray(responseData.getData());
                if(array != null && array.size() > 0){
                    StringBuffer labelsApi = new StringBuffer();
                    StringBuffer valuesApi = new StringBuffer();
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject jsonObject = JSONUtil.parseObj(array.get(i));
                        labelsApi.append(jsonObject.getStr("name")+",");
                        valuesApi.append(jsonObject.getStr("value")+",");
                    }
                    labels = labelsApi.toString();
                    values = valuesApi.toString();
                }
            }
        }else if(dict != null){//通过字典取值
            ISysDictDataService dictDataService = AppCtx.getBean(ISysDictDataService.class);
            List<SysDictData> sysDictData = dictDataService.selectDictDataByType(dict.toString());
            if(sysDictData != null && sysDictData.size() > 0){
                StringBuffer labelsApi = new StringBuffer();
                StringBuffer valuesApi = new StringBuffer();
                for (SysDictData dictData : sysDictData) {
                    labelsApi.append(dictData.getDictLabel()+",");
                    valuesApi.append(dictData.getDictValue()+",");

                    if("Y".equals(dictData.getIsDefault()) && value == null){
                        value = dictData.getDictValue();
                    }
                }
                labels = labelsApi.toString();
                values = valuesApi.toString();
            }
        }


        StringBuilder buf = new StringBuilder();

        if(values != null){

            if(all != null){
                buf.append("<div class='radio-box'>");
                buf.append("<input name='"+id+"' value='' type='radio'/><label >"+all+"</label>");
                buf.append("</div>");
            }

            String[] arr1 = values.toString().split(",");
            String[] arr2 = labels.toString().split(",");
            for (int i = 0; i < arr1.length; i++) {
                String selected = "";
                if(value != null && value.toString().equals(arr1[i])){
                    selected = "checked";
                }
                buf.append("<div class='radio-box'>");
                buf.append("<input name='"+id+"' value='"+arr1[i]+"' type='radio' "+selected+"/><label >"+arr2[i]+"</label>");
                buf.append("</div>");
            }
        }else{
            buf.append(getBodyContent().getBody());
        }

        try {
            ctx.byteWriter.writeString(buf.toString());
            doBodyRender();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

